package com.xinchao.ck_mips.utils.task;

import java.util.concurrent.PriorityBlockingQueue;

public class TaskManager {
    private PriorityBlockingQueue<Task> mQueue;
    private TaskDispatcher[] mTaskDispatchers;
    private volatile static TaskManager ourInstance;
    private int max_pool_size;

    private TaskManager() {
        max_pool_size = Runtime.getRuntime().availableProcessors() * 2;
        if (max_pool_size == 0) {
            max_pool_size = 4;
        }
        mTaskDispatchers = new TaskDispatcher[max_pool_size];
        mQueue = new PriorityBlockingQueue<>();
        startTask();
    }

    public static TaskManager getInstance() {
        if (ourInstance == null) {
            synchronized (TaskManager.class) {
                if (ourInstance == null) {
                    ourInstance = new TaskManager();

                }
            }
        }

        return ourInstance;
    }

    public void stop() {
        if (mTaskDispatchers != null) {
            int len = mTaskDispatchers.length;
            TaskDispatcher dispatcher;
            for (int i = 0; i < len; i++) {
                dispatcher = mTaskDispatchers[i];
                if (dispatcher != null) {
                    dispatcher.quit();
                }

            }
        }
    }

    public void startTask() {
        stop();
        for (int i = 0; i < mTaskDispatchers.length; i++) {
            TaskDispatcher dispatcher = new TaskDispatcher(mQueue);
            mTaskDispatchers[i] = dispatcher;
            dispatcher.start();
        }
    }

    public void cancelAll() {
        stop();
        mQueue.clear();
    }

    public void cancelTask(Task task) {
        if (task != null) {
            task.cancel();
        }
    }

    public void addTask(Task task) {
        mQueue.add(task);
    }
}
